package cn.com.my.gallery;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter4.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

public class ImageFolderActivity extends AppCompatActivity {
    HashMap<String, List<ImageBean>> imagesByDirectory = new HashMap<>();
    private static final String TAG = "ImageActivity";
    private ImageFolderAdapter adapter;
    private RecyclerView rvList;
    private EditText etName;
    private Button btnSearch;
    int spanCount = 3; // 4列
    int spacing = 10; // 10dp间距
    List<ImageFolderBean> imageFolderBeans = new ArrayList<>();
    List<ImageFolderBean> tempFolders = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img);
        adapter = new ImageFolderAdapter(tempFolders);
        rvList = findViewById(R.id.rvPhoto);
        etName = findViewById(R.id.etName);
        btnSearch = findViewById(R.id.btnSearch);
        boolean includeEdge = true; // 包含边缘
        rvList.setLayoutManager(new GridLayoutManager(this, spanCount));
        rvList.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener<ImageFolderBean>() {
            @Override
            public void onClick(@NonNull BaseQuickAdapter<ImageFolderBean, ?> baseQuickAdapter, @NonNull View view, int i) {
                ImageFolderBean imageFolderBean = adapter.getItem(i);
                Intent intent = new Intent(ImageFolderActivity.this, ImageActivity.class);
                intent.putExtra("images", imageFolderBean);
                startActivity(intent);

            }
        });
        rvList.setAdapter(adapter);
        new Thread(new Runnable() {
            @Override
            public void run() {
                fetchImages();
            }
        }).start();
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String keyName = etName.getText().toString();
                search(keyName);

            }
        });
        etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                search(editable.toString());
            }
        });
    }

    private void search(String keyName) {
        tempFolders.clear();
        for (ImageFolderBean imageFolderBean : imageFolderBeans) {
            if (imageFolderBean.folder.toLowerCase().contains(keyName.toLowerCase())) {
                tempFolders.add(imageFolderBean);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        if (tempFolders.size() != imageFolderBeans.size()) {
            tempFolders.clear();
            tempFolders.addAll(imageFolderBeans);
            adapter.notifyDataSetChanged();
            return;
        }
        super.onBackPressed();
    }

    private void fetchImages() {
        String[] projection = new String[]{
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME
        };

        try (Cursor cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,
                null,
                null
        )) {
            int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
            int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
            int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
            int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            int bucketColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);

            while (cursor.moveToNext()) {
                long id = cursor.getLong(idColumn);
                String name = cursor.getString(nameColumn);
                int size = cursor.getInt(sizeColumn);
                String data = cursor.getString(dataColumn);
                String bucket = cursor.getString(bucketColumn);
                if (!TextUtils.isEmpty(bucket)) {
                    ImageBean imageBean = new ImageBean();
                    imageBean.id = id;
                    imageBean.name = name;
                    imageBean.size = size;
                    imageBean.data = data;
                    imageBean.bucket = bucket;
                    if (!imagesByDirectory.containsKey(bucket)) {
                        imagesByDirectory.put(bucket, new ArrayList<>());
                    }
                    imagesByDirectory.get(bucket).add(imageBean);
                }

                // 处理每张图片，例如添加到按目录分类的HashMap中
                Log.d("Image", "ID: " + id + ", Name: " + name + ", Size: " + size + ", Path: " + data + ", Bucket: " + bucket);
            }
            List<String> keys = new ArrayList<>();
            for (String s : imagesByDirectory.keySet()) {
                keys.add(s);
            }
            keys.sort(new Comparator<String>() {
                @Override
                public int compare(String s, String t1) {
                    return s.compareTo(t1);
                }
            });

            for (String key : keys) {
                Log.d(TAG, "fetchImages: " + key + " 大小 " + imagesByDirectory.get(key).size());
                ImageFolderBean imageFolderBean = new ImageFolderBean();
                imageFolderBean.folder = key;
                imageFolderBean.imageBeans = new ArrayList<>();
                imageFolderBean.imageBeans.addAll(imagesByDirectory.get(key));
                imageFolderBean.size = imagesByDirectory.get(key).size();
                imageFolderBeans.add(imageFolderBean);
            }
            rvList.post(new Runnable() {
                @Override
                public void run() {
                    tempFolders.addAll(imageFolderBeans);
                    adapter.notifyDataSetChanged();
                }
            });

        }
    }
}
